package com.bi.bitest.bao;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.bi.bitest.bao.entity.AlbumDetail.Tracks;
import com.bi.bitest.bao.entity.AlbumPlay.AlbumPlay;
import com.bi.bitest.bao.service.PlayService;
import com.bi.bitest.bao.tasks.AlbumPlayTask;
import com.bi.bitest.bao.tasks.TaskCallback;
import com.bi.bitest.bao.tasks.TaskResult;
import com.bi.bitest.bao.utils.VolleyUtils;

import java.util.ArrayList;


public class AlbumPlayActivity extends Activity implements TaskCallback, View.OnClickListener {

    private Intent intent;
    private String trackId;
    private int position;
    private ArrayList<Tracks> list;

    private TextView tv_title,tv_jindu;
    private ImageView iv_large,iv_play,iv_next,iv_previous;
    private String playUrl;
    private SeekBar bar;

    private boolean isPlaying=false;
    private PrgReceiver prgReceiver;
    private LocalBroadcastManager lbMgr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_album_play);


        intent = getIntent();
        trackId = intent.getStringExtra("id");
        position = intent.getIntExtra("position", -1);
        list = intent.getParcelableArrayListExtra("tracks");

        tv_title = (TextView) findViewById(R.id.tv_dingbu_playalbum);
        tv_jindu= (TextView) findViewById(R.id.tv_jindu_albumplay);
        iv_large = (ImageView) findViewById(R.id.iv_large_playalbum);
        iv_next= (ImageView) findViewById(R.id.iv_next_playalbum);
        iv_previous= (ImageView) findViewById(R.id.iv_previous_playalbum);
        iv_play= (ImageView) findViewById(R.id.iv_play_playalbum);
        bar= (SeekBar) findViewById(R.id.progress);

        lbMgr=LocalBroadcastManager.getInstance(getApplicationContext());
        prgReceiver=new PrgReceiver();
        lbMgr.registerReceiver(prgReceiver, new IntentFilter(Constants.ACTION_PROGRESS));

        initEvent();

        AlbumPlayTask task = new AlbumPlayTask(AlbumPlayActivity.this, trackId);
        task.execute();
        isPlaying = true;
        iv_play.setImageResource(R.drawable.album_pause);
    }

    private void initEvent() {
        iv_previous.setOnClickListener(this);
        iv_next.setOnClickListener(this);
        iv_play.setOnClickListener(this);
        bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO 拖动结束时的方法
                //获取当前拖动的位置
                int seekPosition=seekBar.getProgress();
                //向播放组件组件发送广播
                Intent intent=new Intent(Constants.ACTION_SEEKTO);
                intent.putExtra(Constants.EXTRA_PROGREES_CUR, seekPosition);

                lbMgr.sendBroadcast(intent);//发送广播（在Service组件内接收）
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch(v.getId())
        {
            case R.id.iv_previous_playalbum:
                isPlaying = false;
                iv_play.setImageResource(R.drawable.album_play);
                iv_play.setEnabled(false);

                Intent intentpre=new Intent(AlbumPlayActivity.this,PlayService.class);
                intentpre.putExtra(Constants.EXTRA_CHANGE,false);
                intentpre.putExtra("isFirst", false);
                startService(intentpre);
/////先停止播放
                position-=1;
                Tracks track=list.get(position);
                AlbumPlayTask task = new AlbumPlayTask(AlbumPlayActivity.this, track.getTrackId()+"");
                task.execute();
                break;
            case R.id.iv_play_playalbum:
                Intent intent=new Intent(AlbumPlayActivity.this,PlayService.class);
                intent.putExtra(Constants.EXTRA_CHANGE,false);
                intent.putExtra("isFirst",false);
                startService(intent);
                isPlaying=!isPlaying;
                if(isPlaying){
                    iv_play.setImageResource(R.drawable.album_pause);
                }else{
                    iv_play.setImageResource(R.drawable.album_play);
                }
                break;
            case R.id.iv_next_playalbum:
                isPlaying = false;
                iv_play.setImageResource(R.drawable.album_play);

                Intent intentnext=new Intent(AlbumPlayActivity.this,PlayService.class);
                intentnext.putExtra(Constants.EXTRA_CHANGE,false);
                intentnext.putExtra("isFirst", false);
                startService(intentnext);
                iv_play.setEnabled(false);
/////先停止播放

                position+=1;
                Tracks tracknext=list.get(position);
                AlbumPlayTask tasknext = new AlbumPlayTask(AlbumPlayActivity.this, tracknext.getTrackId()+"");
                tasknext.execute();

                break;
            default:break;
        }
    }


    @Override
    public void onTaskFinished(TaskResult result) {
        if (result != null) {
            if (result.action == Constants.TASK_ALBUM_PLAY) {
                if (result.retCode == Constants.TASK_RESULT_OK) {
                    Object data = result.data;
                    if (data != null) {
                        if (data instanceof AlbumPlay) {

                            AlbumPlay albumPlay=(AlbumPlay)data;
                            tv_title.setText(albumPlay.getTitle());
                            VolleyUtils.getLoader(this).get(albumPlay.getCoverLarge(), ImageLoader.getImageListener(
                                    iv_large, R.mipmap.ic_launcher, android.R.drawable.ic_menu_delete));
                //---------------开启服务播放音乐
                            Intent intent = new Intent(AlbumPlayActivity.this, PlayService.class);
                            intent.putExtra(Constants.EXTRA_CHANGE, true);
                            playUrl = albumPlay.getPlayUrl32();
                            intent.putExtra("songLink", playUrl);

                           /* bar.setProgress(0);
                            tv_jindu.setText("00:00/00:00");*/

                            startService(intent);

                        }
                    }
                }
            }
        }
    }



    class PrgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO 接收播放服务组件中发送的进度广播
            int max=intent.getIntExtra(Constants.EXTRA_PROGREES_MAX,0);
            int cur=intent.getIntExtra(Constants.EXTRA_PROGREES_CUR,0);
            boolean kai=intent.getBooleanExtra("kai",false);
            if(kai==true){
                iv_play.setEnabled(true);
                iv_play.setImageResource(R.drawable.album_pause);
            isPlaying=true;
            }
            //TODO 换图片
            bar.setMax(max);
            bar.setProgress(cur);

            tv_jindu.setText(formatTime(cur / 1000) + "/" + formatTime(max / 1000));
        }
    }
    private String formatTime(int s){
        StringBuilder builder=new StringBuilder();

        int m=s/60; //获取分钟
        s=s%60; //获取秒数

        builder.append(m/10).append(m%10)
                .append(":")
                .append(s/10).append(s%10);

        return builder.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        lbMgr.unregisterReceiver(prgReceiver);//取消注册本地广播接收器
    }

}